package com.ruoyi.framework.web.service;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class GiteeLoginService
{
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysUserService userService;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param userId 第三方应用标识
     * @return 结果
     */
    public String login(String username, String userId)
    {

       SysUser sysUser= userService.selectUserByUserName("gitee_"+userId);

       if(sysUser==null){//
           sysUser=new SysUser();
           sysUser.setUserName("gitee_"+userId);
           sysUser.setPassword(SecurityUtils.encryptPassword("gitee_123456"));
           sysUser.setNickName(username);
           //添加用户
          int addCount= userService.insertUser(sysUser);
          //添加用户权限  自行完善

           sysUser= userService.selectUserByUserName("gitee_"+userId);
       }

        LoginUser loginUser = new LoginUser();



        //设置用户权限  自行编写代码获取用户权限设置给当前用户
        loginUser.setPermissions(new HashSet<String>());

        loginUser.setUser(sysUser);

        //记录登录操作日志
        recordLoginInfo(loginUser.getUserId());

        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
